import base64
import os
import subprocess
import threading
from io import BytesIO

from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog
from PySide6.QtGui import QPixmap
from PySide6.QtCore import QEvent, Qt, Signal, Slot

import lasio
from matplotlib import pyplot as plt

from uipy.mainWindow import Ui_MainWindow as mw

from drawLines import DrawLinesAndGetImg
from showBasicInfo import ShowBasicInfo
from drawGreyImg import DrawGreyImg
from editImgSIN import create_image_window
from internal.dynamicDraw.dynamicDraw import ConsumeMessages


class MyWindow(QMainWindow, mw):
    # 信号，用来传递绘图所需的数据
    update_plot_signal = Signal(list)

    def __init__(self):
        super().__init__()

        self.image_window = None
        self.message_consumer_thread = None  # 用于存储线程实例

        # 设置UI
        self.setupUi(self)

        # 绑定事件
        self.bind()

        # 用于存储当前显示的图片路径
        self.current_lines_image_path = "./asset/default/default.png"
        self.current_grey_image_path = "./asset/default/default.png"
        self.current_grey_image_SIN_path = "./asset/default/default.png"

    def bind(self):
        # 绑定上传文件的动作到函数
        self.actionUpload.triggered.connect(self.loadFileAndDrawGammaLines)
        self.commandLinkButton.clicked.connect(self.imgOperateSIN)
        self.commandLinkButton_3D.clicked.connect(self.display3D)
        self.pushButton_startConsume.clicked.connect(self.start_consuming_messages_thread)


    def start_consuming_messages_thread(self):
        if self.message_consumer_thread is not None and self.message_consumer_thread.is_alive():
            # 如果已有线程在运行，则不创建新线程
            print("Message consumer thread is already running.")
            return

        # 创建一个新的线程来执行 Consume_Messages 函数
        self.message_consumer_thread = threading.Thread(target=ConsumeMessages)
        # 将守护线程设置为True，这样当主线程退出时，该线程也会被强制结束
        self.message_consumer_thread.daemon = True
        # 启动线程
        self.message_consumer_thread.start()

    def display3D(self):
        path = self.lineEdit_texturePath.text()
        print(f"using texture {path}")

        current_dir = os.getcwd()

        # 定义要运行的命令及其参数
        cmd = [current_dir + "\\asset\\OpenGL\\cmake-build-debug\\OpenGL.exe", path]

        # 使用 subprocess.run 来运行命令，并通过 cwd 参数更改工作目录
        subprocess.run(cmd, cwd=current_dir + "\\asset\\OpenGL\\cmake-build-debug")

    def imgOperateSIN(self):
        print("啊啊啊")
        # 图片路径
        image_path = "./asset/gammaImg.png"

        # 创建并显示新的 ImageWindow
        self.image_window = create_image_window(image_path)
        self.image_window.windowClosed.connect(self.showSinPic)  # 连接信号到槽
        self.image_window.show()

    # 子窗口关闭时，将标注了正弦特征的图片显示在原图片右侧
    def showSinPic(self):
        self.current_grey_image_SIN_path = QPixmap("./asset/SIN.png")
        self.updateImage()

    def loadFileAndDrawGammaLines(self):
        # 打开文件对话框选择LAS文件
        filePath, _ = QFileDialog.getOpenFileName(self, '选择LAS文件', '', 'LAS文件(*.las)')
        if not filePath:
            return  # 如果用户取消了文件选择，则直接返回

        print("开始读")
        las = lasio.read(filePath)
        print("读完了")

        # 展示las文件头部信息
        ShowBasicInfo(self, las)

        # 绘制伽马射线曲线并保存为图像
        print("开始画")
        DrawLinesAndGetImg(las)
        DrawGreyImg(las)
        self.current_lines_image_path = "asset/gammaLines.png"
        self.current_grey_image_path = "asset/gammaImg.png"
        self.updateImage()
        print("画完了")

    # 窗口大小改变时，更新图像大小
    def updateImage(self):
        if self.current_lines_image_path is None:
            return
        if self.current_grey_image_path is None:
            return

        # 加载图片
        lines_pixmap = QPixmap(self.current_lines_image_path)
        grey_pixmap = QPixmap(self.current_grey_image_path)
        sin_pixmap = QPixmap(self.current_grey_image_SIN_path)

        # 获取 QLabel 的尺寸
        lines_label_width = self.label_showCurveImg.width()
        lines_label_height = self.label_showCurveImg.height()
        grey_label_width = self.label_showGammaImg.width()
        grey_label_height = self.label_showGammaImg.height()
        sin_label_width = self.label_showEditedGammaImg.width()
        sin_label_height = self.label_showEditedGammaImg.height()

        # 缩放图片以适应 QLabel 尺寸，同时保持宽高比
        lines_scaled_pixmap = lines_pixmap.scaled(lines_label_width, lines_label_height, Qt.KeepAspectRatio,
                                                  Qt.SmoothTransformation)
        grey_scaled_pixmap = grey_pixmap.scaled(grey_label_width, grey_label_height, Qt.KeepAspectRatio,
                                                Qt.SmoothTransformation)
        sin_scaled_pixmap = sin_pixmap.scaled(sin_label_width, sin_label_height, Qt.KeepAspectRatio,
                                              Qt.SmoothTransformation)

        # 在 QLabel 中显示图片
        self.label_showCurveImg.setPixmap(lines_scaled_pixmap)
        self.label_showGammaImg.setPixmap(grey_scaled_pixmap)
        self.label_showEditedGammaImg.setPixmap(sin_scaled_pixmap)

    def resizeEvent(self, event: QEvent) -> None:
        # 调用父类的 resizeEvent 方法
        super().resizeEvent(event)
        # 当窗口大小改变时更新图片
        self.updateImage()


if __name__ == '__main__':
    app = QApplication([])
    window = MyWindow()
    window.show()
    app.exec()

    # 文件夹路径
    folder_path = "./asset"

    # 遍历文件夹中的每个文件并删除
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        # 确保是文件而不是子目录
        if os.path.isfile(file_path):
            try:
                os.remove(file_path)
                print(f"已删除 {file_path}")
            except Exception as e:
                print(f"无法删除 {file_path}. 原因: {e}")
